import 'package:flutter_bilibili/cache/hi_cache.dart';
import 'package:flutter_bilibili/const/cache_const.dart';
import 'package:flutter_bilibili/const/http_const.dart';

/// 基础请求
abstract class BaseRequest {
  /// 是否使用https
  bool useHttps = true;

  /// 域名
  String authority() {
    return 'cn.apihz.cn';
  }

  /// 请求方式
  HttpMethod httpMethod();

  /// 是否需要登录
  bool needLogin();

  /// 存储header
  Map<String, dynamic> header = Map();

  /// 添加header
  BaseRequest addHeader(String k, Object v) {
    header[k] = v.toString();
    return this;
  }

  /// 存储参数
  Map<String, String> params = Map();

  /// 添加参数
  BaseRequest add(String k, Object v) {
    params[k] = v.toString();
    return this;
  }

  /// 请求路径path
  String path();

  /// 路径参数
  var pathParams;

  /// 拼接url
  String url() {
    Uri uri;
    var pathStr = path();
    // 拼接path参数
    if (pathParams != null) {
      if (path().endsWith('/')) {
        pathStr = '${path()}$pathParams';
      } else {
        pathStr = '${path()}/$pathParams';
      }
    }
    // http和https切换
    if (useHttps) {
      uri = Uri.https(authority(), pathStr, params);
    } else {
      uri = Uri.http(authority(), pathStr, params);
    }

    if (needLogin()) {
      // todo:需要登录的接口自动从缓存中读取token设置在请求头
      addHeader('auth-token', HiCache().get(CacheKey.BOARDING_PASS as String)!);
    }
    return uri.toString();
  }
}
